import { getSotreCouponListApi, postCouponApi } from '@/services/api';
import {
  ModalForm,
  ProFormDigit,
  ProFormInstance,
  ProFormList,
  ProFormSelect,
} from '@ant-design/pro-components';
import { useRequest } from 'ahooks';
import { Col, Form, Result, Row, Tag, message } from 'antd';
import { isEqual } from 'lodash';
import React, { useRef } from 'react';

interface Props {
  open?: boolean;
  info?: any;
  close?: () => void;
  onFinsh?: () => void;
  options?: any;
}
const BindCouponModal: React.FC<Props> = ({
  open,
  close,
  info,
  onFinsh,
  options,
}) => {
  const [form] = Form.useForm<{ name: string; company: string }>();

  const formRef = useRef<ProFormInstance>();

  const { data, loading } = useRequest(
    async () => {
      if (!info?.id) return [];
      const _res = await getSotreCouponListApi(info?.id);

      return _res?.data?.map((e) => {
        return {
          value: e.code,
          label: (
            <>
              {e.title}{' '}
              <Tag bordered={false} color="blue">
                {e.code}
              </Tag>
            </>
          ),
          info: e?.info,
        };
      });
    },
    {
      refreshDeps: [info],
      onSuccess: (_tes) => {
        formRef.current?.setFieldsValue({
          users: _tes?.map((_item) => {
            return {
              coupon: _item?.value,
              frequency: _item?.info?.frequency ?? undefined,
              surplus: _item?.info?.surplus ?? undefined,
            };
          }),
        });
      },
    },
  );

  console.log('data', data);

  return (
    <ModalForm
      formRef={formRef}
      title={'优惠券设置'}
      form={form}
      open={open}
      width={700}
      onOpenChange={(visible) => {
        if (!visible) {
          close?.();
        }
      }}
      autoFocusFirstInput
      onFinish={async (values) => {
        try {
          await postCouponApi(
            info?.id,
            values.users?.map((_item) => {
              return {
                ..._item,
                frequency: _item?.frequency ?? '',
              };
            }),
          );
          onFinsh?.();
          message.success('配置优惠券成功');
          // 不返回不会关闭弹框
          return true;
        } catch (error) {}
      }}
      initialValues={{
        users: data?.map((_item) => {
          return {
            coupon: _item?.value,
            frequency: _item?.info?.frequency ?? undefined,
            surplus: _item?.info?.surplus ?? undefined,
          };
        }),
      }}
      modalProps={{ loading: loading }}
    >
      <ProFormList
        deleteIconProps={false}
        creatorButtonProps={false}
        name="users"
        min={1}
        copyIconProps={false}
      >
        <Row gutter={16}>
          <Col>
            <ProFormSelect
              disabled
              name="coupon"
              label="优惠券"
              width="md"
              rules={[
                {
                  required: true,
                },
              ]}
              options={data ?? []}
              placeholder="请选择优惠券"
              fieldProps={{
                showSearch: true,
                popupMatchSelectWidth: false,
              }}
            ></ProFormSelect>
          </Col>
          <Col>
            {' '}
            <ProFormDigit
              width="xs"
              label="总次数"
              name="frequency"
              // rules={[
              //   {
              //     required: true,
              //   },
              // ]}
              fieldProps={{
                type: 'number',
                precision: 0,
                min: 1,
              }}
            />
          </Col>

          <Col>
            <ProFormDigit
              label="剩余次数"
              name="surplus"
              width="xs"
              // rules={[
              //   {
              //     required: true,
              //   },
              // ]}
              fieldProps={{
                type: 'number',
                precision: 0,
                min: 1,
              }}
              disabled
            />
          </Col>
        </Row>
      </ProFormList>

      {!data && (
        <Result status="error" title="当前商户没有绑定任何优惠券"></Result>
      )}
    </ModalForm>
  );
};

export default React.memo(BindCouponModal, (prev, next) => isEqual(prev, next));
